<script setup>

import { ref,defineProps } from 'vue'
import axios from "axios";
import {ElLoading, ElMessage} from "element-plus";

const props = defineProps({
  orders: {
    type: Array,
    required: true
  }
})

const getOrderButtons = (orderStatus) => {
  switch (orderStatus) {
    case 1:  // 待付款
      return [
        { label: '去支付', type: 'primary', action: payOrder },
        { label: '取消订单', type: 'danger', action: cancelPurchase }
      ];
    case 2: // 待发货
      return [
        { label: '提醒发货', type: 'primary', action: remindDelivery },
        { label: '修改地址', type: 'warning', action: modifyAddress }
      ];
    case 3: // 待收货
      return [
        { label: '确认收货', type: 'primary', action: confirmReceipt }
      ];
    case 4: // 待评价
      return [
        { label: '评价', type: 'success', action: comment }
      ];
    default:
      return [];
  }
};


//定义一个生成唯一编码的方法
const generateUniqueCode = ()=>{
  const timestamp = Date.now();
  const randomNum = Math.floor(Math.random() * 100000); // 生成一个 0 到 99999 之间的随机整数
  const uniqueCode = "WNXY_" + timestamp + randomNum.toString().padStart(5, '0');
  return uniqueCode;
}

///////////////////【点击去支付】///////////////////
const payOrder = (orderId) => {
  console.log("执行支付操作", orderId);
  // 实现支付逻辑...

  // 为了解决重复支付问题，前端生成唯一标记
  const uniqueCode = generateUniqueCode();

  //显示加载状态
  const loadingInstance = ElLoading.service({
    fullscreen: true,
    text: '正在跳转到支付页面...',
    spinner: 'el-icon-loading'
  });

  // 发送支付请求
  let paramData = {
    orderId: orderId,
    uniqueCode: uniqueCode
  }
  axios.post('/order/pay',paramData).then(resp=>{

     //ElMessage.success(`支付成功, 订单号：${orderId}`)

      // 跳转到支付页面
      // 添加之前先删除一下，如果单页面，页面不刷新，添加进去的内容会一直保留在页面中，二次调用form表单会出错
      const divForm = document.getElementsByTagName("div");
      if (divForm.length) {
        document.body.removeChild(divForm[0]);
      }
      const div = document.createElement("div");
      div.innerHTML = resp.data; // data就是接口返回的form 表单字符串
      document.body.appendChild(div);
      //document.forms[0].setAttribute("target", "_blank"); // 新开窗口跳转
      document.forms[0].submit()

  }).catch(err => {
     ElMessage.error(`订单: ${orderIdStr}，支付失败：${error.response.data}`)
  })

};
const cancelPurchase = (orderId) => {
  console.log("执行取消购买操作", orderId);
  // 实现取消逻辑...
};
const remindDelivery = (orderId) => {
  console.log("执行提醒发货操作", orderId);
  // 实现提醒逻辑...
};
const confirmReceipt = (orderId) => {
  console.log("实现确认收货的逻辑", orderId);
  // 实现确认收货逻辑...
};
const modifyAddress = () => {
  console.log("执行修改地址操作");
  // 实现修改地址逻辑...
};
const comment = () => {
  console.log("执行评价的操作");
  // 实现评价逻辑...
};

</script>

<template>
  <div>
    <template v-if="orders.length > 0">
      <!-- 显示订单 -->
      <div v-for="(order, index) in orders" :key="index" class="order-middle">
        <el-descriptions>
          <el-descriptions-item label="订单编号">{{ order.orderNum }}</el-descriptions-item>
          <el-descriptions-item label="订单总金额（元）">
            {{ order.totalPrice }}
          </el-descriptions-item>
          <el-descriptions-item label="下单时间">{{ order.createTime }}</el-descriptions-item>
          <el-descriptions-item label="收货人">{{ order.receiver }}</el-descriptions-item>
          <el-descriptions-item label="收货地址">{{ order.address }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ order.phone }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">{{ order.orderStatus }}</el-descriptions-item>
        </el-descriptions>

        <el-table :data="order.orderItem" style="width: 100%" border>
          <el-table-column prop="bookName" label="书籍名称"></el-table-column>
          <el-table-column prop="image" label="书籍图片">
            <template #default="{ row }">
              <el-image style="height: 120px;"
                        :src="$urlImage + row.bookImg"
                        fit="fit">
              </el-image>
            </template>
          </el-table-column>

          <el-table-column prop="buyCount" label="数量" width="100"></el-table-column>
          <el-table-column prop="sumPrice" label="小计" width="100"></el-table-column>
        </el-table>

        <div class="order-footer">
          <!-- 根据订单状态决定显示的按钮 -->
          <el-button
              v-for="button in getOrderButtons(order.status)"
              :key="button.label"
              size="small"
              round
              :type="button.type"
              :icon="button.icon"
              @click="() => button.action(order.id)">
            {{ button.label }}
          </el-button>
        </div>
      </div>
    </template>
    <template v-else>
      <el-empty description="没有查询到订单"></el-empty>
    </template>
  </div>
</template>

<style scoped>
.order-middle {
  border-radius: 5px;
  border: 1px solid #e4e7ed;
  margin-bottom: 20px;
  padding: 10px;
  box-shadow: 0 5px 10px -5px rgba(0, 0, 0, 0.5);
}

.order-footer {
  margin-top: 10px;
  margin-bottom: 5px;
}
</style>
